package membership;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import remoteprocedurecall.RPCDestination;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.simpledb.model.Attribute;
import com.amazonaws.services.simpledb.model.BatchPutAttributesRequest;
import com.amazonaws.services.simpledb.model.CreateDomainRequest;
import com.amazonaws.services.simpledb.model.DeleteAttributesRequest;
import com.amazonaws.services.simpledb.model.DeleteDomainRequest;
import com.amazonaws.services.simpledb.model.Item;
import com.amazonaws.services.simpledb.model.PutAttributesRequest;
import com.amazonaws.services.simpledb.model.ReplaceableAttribute;
import com.amazonaws.services.simpledb.model.ReplaceableItem;
import com.amazonaws.services.simpledb.model.SelectRequest;

public class SimpleDBCalls {

	private final static String myDomain = "ssmMembership";
	private final static String myMembershipItem = "servers";
	private final static String myMembershipItemStatusRunning = "running";

	public static void ssmSetMyMembership(AmazonSimpleDB sdb, String ip,
			String port) throws Exception {
		// Put data into a domain
		List<ReplaceableItem> sampleData = new ArrayList<ReplaceableItem>();
		sampleData.add(new ReplaceableItem(myMembershipItem)
				.withAttributes(new ReplaceableAttribute(ip + ":" + port,
						myMembershipItemStatusRunning, true)));
		sdb.batchPutAttributes(new BatchPutAttributesRequest(myDomain,
				sampleData));
	}

	public static void ssmDeleteServer(AmazonSimpleDB sdb, String ip,
			String port) throws Exception {
		// Put data into a domain
		sdb.deleteAttributes(new DeleteAttributesRequest(myDomain,
				myMembershipItem).withAttributes(new Attribute(ip + ":" + port,
				myMembershipItemStatusRunning)));
	}

	public static void ssmDeleteDomain(AmazonSimpleDB sdb) throws Exception {
		// Put data into a domain
		sdb.deleteDomain(new DeleteDomainRequest(myDomain));
	}

	public static void ssmCreateDomain(AmazonSimpleDB sdb) throws Exception {
		// Put data into a domain
		sdb.createDomain(new CreateDomainRequest(myDomain));
	}

	public static List<RPCDestination> ssmGetServers(AmazonSimpleDB sdb) throws Exception {
		// consistent read? yes
		boolean consistentRead = true;
		// Get all servers
		List<RPCDestination> servers = new ArrayList<RPCDestination>();
		String selectExpression = "select * from " + myDomain;
		SelectRequest selectRequest = new SelectRequest(selectExpression,
				consistentRead);
		selectRequest.setConsistentRead(true);
		for (Item item : sdb.select(selectRequest).getItems()) {
			for (Attribute attribute : item.getAttributes()) {
				servers.add(new RPCDestination(
						attribute.getName().split(":")[0], Integer
								.parseInt(attribute.getName().split(":")[1])));
			}
		}
		return servers;
	}

	public static void main(String[] args) throws Exception {
		/*
		 * Important: Be sure to fill in your AWS access credentials in the
		 * AwsCredentials.properties file before you try to run this sample.
		 * http://aws.amazon.com/security-credentials
		 */
		//AmazonSimpleDB sdb = new AmazonSimpleDBClient(
		//		new PropertiesCredentials(
		//				SimpleDBCalls.class.getResourceAsStream(new String(
		//						"credentials.properties"))));
		
		AWSCredentials awsCredentials = new BasicAWSCredentials("AKIAJAMYO5EPQY5VQ4DA", "fH96pmQ7LhswDb9ORvZK7JGj+b3gplhAbyBa8R0M");
		AmazonSimpleDB sdb = new AmazonSimpleDBClient(awsCredentials);

		System.out.println("===========================================");
		System.out.println("Getting Started with Amazon SimpleDB");
		System.out.println("===========================================\n");

		try {

			System.out.println("Create Domain");
			SimpleDBCalls.ssmCreateDomain(sdb);

			System.out.println("Add server");
			//SimpleDBCalls.ssmSetMyMembership(sdb, "129.123.123.12", "100");
			//SimpleDBCalls.ssmSetMyMembership(sdb, "129.123.123.12", "200");
			//SimpleDBCalls.ssmSetMyMembership(sdb, "129.123.123.12", "300");

			System.out.println("Delete server");
			//SimpleDBCalls.ssmDeleteServer(sdb, "129.123.123.12", "400");

			System.out.println("Display server data");
			List<RPCDestination> svrs = SimpleDBCalls.ssmGetServers(sdb);
			
			boolean inList=false;
			for(RPCDestination rd:svrs){
				System.out.println(rd.destAddress+":"+rd.destPort);
				if(rd.destAddress.equals("129.123.123.12") && rd.destPort==400){
					inList=true;
				}
			}
			
			//if(inList){
			//	System.out.println("I have 129...:400!");
			//} else {
			//	System.out.println("I DONT have 129...:400!");
			//}
			/*
			 * System.out.println("Delete domain");
			 * SimpleDBCalls.ssmDeleteDomain(sdb);
			 */
			//SimpleDBCalls.ssmDeleteDomain(sdb);
		} catch (AmazonServiceException ase) {
			System.out
					.println("Caught an AmazonServiceException, which means your request made it "
							+ "to Amazon SimpleDB, but was rejected with an error response for some reason.");
			System.out.println("Error Message:    " + ase.getMessage());
			System.out.println("HTTP Status Code: " + ase.getStatusCode());
			System.out.println("AWS Error Code:   " + ase.getErrorCode());
			System.out.println("Error Type:       " + ase.getErrorType());
			System.out.println("Request ID:       " + ase.getRequestId());
		} catch (AmazonClientException ace) {
			System.out
					.println("Caught an AmazonClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with SimpleDB, "
							+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ace.getMessage());
		}
	}

}
